﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CommTest
{
    class TextUtility
    {
        public static int chr2int(char chr)
        {
	        if(chr>='0' && chr<='9')
		        return chr-'0';
	        else if(chr>='a' && chr<='f')
		        return chr-'a'+10;
	        else if(chr>='A' && chr<='F')
		        return chr-'A'+10;
	        else
		        return -1;
        }

        public static int hexscan(string str_in, byte[] buffer_out, int buffer_len)
        {
	        int str_len = str_in.Length;
	
	        int last_nibble=-1, nibble=-1;
	        int num = -1;
	
	        int i=0, j=0;
	        for(; i<str_len; i++)
	        {
		        num = -1;
		
		        nibble = chr2int( str_in[i] );
		        if(last_nibble >= 0)
		        {
			        if(nibble >= 0)
				        num = last_nibble * 0x10 + nibble;
			        else
				        num = last_nibble;
		        }
		        else if( (i == str_len-1) && (nibble != -1) )
			        num = nibble;

                if ((num >= 0) && (j < buffer_len))
		        {
			        buffer_out[j++] = (byte)num;
			        last_nibble = -1;
		        }
		        else
			        last_nibble = nibble;
	        }
	
	        return j;
        }
    }
}
